#include "stdafx.h"
#include "LayoutViewEd.h"
#include "LayoutEditor.h"
#include "AllLookFeel.h"

LayoutViewEd::LayoutViewEd()
{
	mLayout = new MGUI_Layout(NULL);

	mImageBox_Back = new MGUI_ImageBox(mLayout);
	mImageBox_Back->SetSkin("BackgroundTile.png");
	mImageBox_Back->SetPickFlag(MGUI_PickFlag::None);
	mImageBox_Back->SetAlign(MGUI_Align::Stretch);

	mRectEd = new RectEd(mLayout);
	mRectEd->SetOrder(1000);

	mRectEd->evRectChanged += OnRectEdChanged(this, &LayoutViewEd::OnRectEdChanged_);
	LayoutEditor::Instance()->eventRectChanged += OnEditRectChanged(this, &LayoutViewEd::OnEditRectChanged_);
}

LayoutViewEd::~LayoutViewEd()
{
	delete mLayout;
}

void LayoutViewEd::Layout()
{
	MGUI_Rect rect;

	rect.x0 = 256;
	rect.y0 = 32;
	rect.x1 = MGUI_Engine::Instance()->GetRect().x1 - 256;
	rect.y1 = MGUI_Engine::Instance()->GetRect().y1 - 32;

	int skinW = rect.x1 - rect.x0 + 1;
	int skinH = rect.y1 - rect.y0 + 1;
	int backW = mImageBox_Back->GetSkin()->GetWidth();
	int backH = mImageBox_Back->GetSkin()->GetHeight();

	mImageBox_Back->SetUVRect(MGUI_RectF(0, 0, skinW / (float)backW, skinH / (float)backH));

	mLayout->SetRect(rect);
}

void LayoutViewEd::OnRectEdChanged_(MGUI_Rect rect)
{
	MGUI_Widget * widget = LayoutEditor::Instance()->GetEditWidget();
	MGUI_Layout * layout = LayoutEditor::Instance()->GetEditLayout();

	if (widget == NULL)
		return ;

	if (widget != layout)
	{
		MGUI_Rect ptRect = layout->GetRect();

		rect.x0 -= ptRect.x0;
		rect.x1 -= ptRect.x0;
		rect.y0 -= ptRect.y0;
		rect.y1 -= ptRect.y0;
	}

	LayoutEditor::Instance()->notifyRectChanged(rect);
}

void LayoutViewEd::OnEditRectChanged_(MGUI_Rect rect)
{
	MGUI_Widget * widget = LayoutEditor::Instance()->GetEditWidget();
	MGUI_Layout * layout = LayoutEditor::Instance()->GetEditLayout();

	if (widget == NULL)
		return ;

	if (widget != layout)
	{
		MGUI_Rect ptRect = layout->GetRect();

		rect.x0 += ptRect.x0;
		rect.x1 += ptRect.x0;
		rect.y0 += ptRect.y0;
		rect.y1 += ptRect.y0;
	}

	mRectEd->SetEditRect(rect);
}
